#!/usr/bin/env python3
"""
病历掌上查接口服务启动脚本

快速启动和测试接口服务
"""

import argparse
import sys
import os
import subprocess
from pathlib import Path

# 添加src目录到Python路径
current_dir = Path(__file__).parent
src_dir = current_dir / "src"
sys.path.insert(0, str(src_dir))

def create_env_file():
    """创建环境配置文件"""
    env_example = current_dir / ".env.example"
    env_file = current_dir / ".env"

    if not env_file.exists() and env_example.exists():
        print("创建 .env 文件...")
        env_file.write_text(env_example.read_text())
        print("请编辑 .env 文件以配置您的环境")

def check_dependencies():
    """检查依赖是否安装"""
    try:
        import fastapi
        import uvicorn
        import pydantic
        print("✓ 依赖检查通过")
        return True
    except ImportError as e:
        print(f"✗ 依赖缺失: {e}")
        print("请运行: pip install -e .")
        return False

def start_dev_server(host="0.0.0.0", port=8000, reload=True):
    """启动开发服务器"""
    print(f"启动开发服务器...")
    print(f"访问地址: http://{host}:{port}")
    print(f"API文档: http://{host}:{port}/docs")
    print(f"健康检查: http://{host}:{port}/health")

    try:
        import uvicorn
        uvicorn.run(
            "medical_report_api.main:app",
            host=host,
            port=port,
            reload=reload,
            log_level="info"
        )
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"启动失败: {e}")
        sys.exit(1)

def run_tests():
    """运行测试"""
    print("运行测试...")
    try:
        result = subprocess.run([
            sys.executable, "-m", "pytest", "tests/", "-v"
        ], capture_output=True, text=True)

        print(result.stdout)
        if result.stderr:
            print("错误输出:", result.stderr)

        return result.returncode == 0
    except FileNotFoundError:
        print("未安装pytest，请运行: pip install pytest")
        return False

def generate_test_data():
    """生成测试数据"""
    try:
        from medical_report_api.services.mock_data import generate_mock_reports

        print("生成测试数据...")
        reports = generate_mock_reports(
            patient_name="测试患者",
            start_time="2024-01-01 00:00:00",
            end_time="2024-12-31 23:59:59"
        )

        print(f"生成了 {len(reports)} 条测试报告数据")

        # 显示前几条数据
        for i, report in enumerate(reports[:3]):
            print(f"报告 {i+1}: {report.item} - {report.time}")

        return True
    except Exception as e:
        print(f"生成测试数据失败: {e}")
        return False

def test_api_endpoint():
    """测试API端点"""
    import requests
    import json

    base_url = "http://localhost:8000"

    # 测试健康检查
    try:
        print("测试健康检查端点...")
        response = requests.get(f"{base_url}/health", timeout=5)
        if response.status_code == 200:
            print("✓ 健康检查通过")
        else:
            print(f"✗ 健康检查失败: {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"✗ 无法连接到服务器: {e}")
        return False

    # 测试报告查询
    print("测试报告查询端点...")
    test_data = {
        "medical_card_number": "11009009",
        "id_card": "370101200001010001",
        "start_time": "2024-01-01 00:00:00",
        "end_time": "2024-12-31 23:59:59",
        "patient_name": "测试患者"
    }

    try:
        response = requests.post(
            f"{base_url}/api/v1/reports/main",
            json=test_data,
            timeout=10
        )

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                print(f"✓ 报告查询成功，返回 {len(result['data']['report'])} 条记录")
                return True
            else:
                print(f"✗ 报告查询业务失败: {result.get('msg')}")
                return False
        else:
            print(f"✗ 报告查询HTTP失败: {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"✗ 报告查询请求失败: {e}")
        return False

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="病历掌上查接口服务启动工具")

    parser.add_argument(
        "action",
        choices=["start", "test", "data", "check", "all"],
        default="start",
        nargs="?",
        help="执行的操作: start(启动服务), test(运行测试), data(生成测试数据), check(检查API), all(完整流程)"
    )

    parser.add_argument("--host", default="0.0.0.0", help="服务器主机地址")
    parser.add_argument("--port", type=int, default=8000, help="服务器端口")
    parser.add_argument("--no-reload", action="store_true", help="禁用热重载")

    args = parser.parse_args()

    # 创建环境文件
    create_env_file()

    # 检查依赖
    if not check_dependencies():
        sys.exit(1)

    if args.action == "start":
        start_dev_server(args.host, args.port, not args.no_reload)

    elif args.action == "test":
        success = run_tests()
        sys.exit(0 if success else 1)

    elif args.action == "data":
        success = generate_test_data()
        sys.exit(0 if success else 1)

    elif args.action == "check":
        success = test_api_endpoint()
        sys.exit(0 if success else 1)

    elif args.action == "all":
        print("执行完整流程...")

        # 1. 生成测试数据
        if not generate_test_data():
            sys.exit(1)

        # 2. 运行测试
        if not run_tests():
            print("⚠️  测试失败，但仍将启动服务")

        # 3. 启动服务
        print("\n启动服务...")
        start_dev_server(args.host, args.port, not args.no_reload)

if __name__ == "__main__":
    main()